Phoenix LiveView

2019-03-31

I'm playing with Phoenix LiveView this weekend to port a little Goban I wrote in Elm last year to Elixir.

One feature that's missing from LiveView currently is handling hovering, which I use to show where you can place your stones. I found the delightfully small source for the Javascript side of LiveView.

It's really easy to read and understand (given you're a bit familiar with event handling in JS), and it's also pretty straight-forward to add new events. The only drawback is that I have to duplicate closestPhxBinding, PHX_VIEW, and PHX_VIEW_SELECTOR, so hopefully they won't change too often.

function closestPhxBinding(el, binding) {
  do {
    if(el.matches(`[${binding}]`)){ return el }
    el = el.parentElement || el.parentNode
  } while(el !== null && el.nodeType === 1 && !el.matches("[data-phx-view]"))
  return null
}

window.addEventListener("mouseover", e => {
  const outBinding = liveSocket.binding("mouseout")
  const overBinding = liveSocket.binding("mouseover")

  const target = closestPhxBinding(e.target, overBinding)
  const overPhxEvent = target && target.getAttribute(overBinding)
  const outPhxEvent = target && target.getAttribute(outBinding)

  if(!overPhxEvent || !outBinding){ return }

  function outHandler(e) {
    target.removeEventListener("mouseout", outHandler, false)
    e.preventDefault()
    liveSocket.owner(target, view => view.pushEvent("mouseout", target, outPhxEvent))
  }

  target.addEventListener("mouseout", outHandler, false)

  e.preventDefault()
  liveSocket.owner(target, view => view.pushEvent("mouseover", target, overPhxEvent))
}, false)

I'll just share this here because the project doesn't allow for new features yet and it might come in handy for someone.